<?php
// 连接数据库

$host = 'localhost:3306';
$user = 'root';
$pwd = 'root';
$dbname = 'kaola';

$con = mysqli_connect($host, $user, $pwd, $dbname);

// 测试数据库是否链接成功
if (!$con) {

  die('数据库连接失败');   //die这个方法结束整个php语句
}

// 最终的结果返回给前端

$result = [];

// 规定前端必须用username和password传参数

$name = $_POST['username'];
$pwd = $_POST['password'];

if ($name && $pwd) {

  //1.数据库查询是否有这个名字
  $sql = "SELECT *FROM user WHERE username='$name'";

  // 2.运行sql语句，用mysqli_query方法
  $run = mysqli_query($con, $sql);

  $obj = mysqli_fetch_array($run);

  //  echo(json_encode($obj));
  if ($obj) {
    $result['status'] = false;
    $result['msg'] = '账号已经被注册';
  } else {
    // 1.插入这个数据
    $sql = "INSERT INTO user(username,password) VALUES('$name','$pwd')";

    // 2.运行sql语句
    $run = mysqli_query($con, $sql);

    if ($run > 0) {
      $result['status'] = true;
      $result['msg'] = '注册成功';
    } else {
      $result['status'] = false;
      $result['msg'] = '数据库错误';
    }
  }
} else {
  $result['status'] = false;
  $result['msg'] = '前端数据有误';
}

echo (json_encode($result, JSON_UNESCAPED_UNICODE));
